
"""
"""
import time
from vnpy.trader.event import EVENT_TIMER
from vnpy.trader.utility import get_folder_path
from vnpy.trader.object import (
    TickData,
    OrderData,
    OrderDataOp,
    TradeData,
    PositionData,
    AccountData,
    ContractData,
    OrderRequest,
    CancelRequest,
    SubscribeRequest,
    LogData
)
from vnpy.trader.gateway import BaseGateway
from vnpy.trader.constant import (
    Direction,
    Offset,
    Exchange,
    OrderType,
    Product,
    Status,
    OptionType
)
from vnpy.api.ctp import (
    MdApi,
    TdApi,
    THOST_FTDC_OAS_Submitted,
    THOST_FTDC_OAS_Accepted,
    THOST_FTDC_OAS_Rejected,
    THOST_FTDC_OST_NoTradeQueueing,
    THOST_FTDC_OST_PartTradedQueueing,
    THOST_FTDC_OST_AllTraded,
    THOST_FTDC_OST_Canceled,
    THOST_FTDC_D_Buy,
    THOST_FTDC_D_Sell,
    THOST_FTDC_PD_Long,
    THOST_FTDC_PD_Short,
    THOST_FTDC_OPT_LimitPrice,
    THOST_FTDC_OPT_AnyPrice,
    THOST_FTDC_OF_Open,
    THOST_FTDC_OFEN_Close,
    THOST_FTDC_OFEN_CloseYesterday,
    THOST_FTDC_OFEN_CloseToday,
    THOST_FTDC_PC_Futures,
    THOST_FTDC_PC_Options,
    THOST_FTDC_PC_SpotOption,
    THOST_FTDC_PC_Combination,
    THOST_FTDC_CP_CallOptions,
    THOST_FTDC_CP_PutOptions,
    THOST_FTDC_HF_Speculation,
    THOST_FTDC_CC_Immediately,
    THOST_FTDC_FCC_NotForceClose,
    THOST_FTDC_TC_GFD,
    THOST_FTDC_VC_AV,
    THOST_FTDC_TC_IOC,
    THOST_FTDC_VC_CV,
    THOST_FTDC_AF_Delete
)
import sys
import pytz
from datetime import datetime
from time import sleep

import traceback
from vnpy.gateway.ctp import CtpGateway


STATUS_CTP2VT = {
    THOST_FTDC_OAS_Submitted: Status.SUBMITTING,
    THOST_FTDC_OAS_Accepted: Status.SUBMITTING,
    THOST_FTDC_OAS_Rejected: Status.REJECTED,
    THOST_FTDC_OST_NoTradeQueueing: Status.NOTTRADED,
    THOST_FTDC_OST_PartTradedQueueing: Status.PARTTRADED,
    THOST_FTDC_OST_AllTraded: Status.ALLTRADED,
    THOST_FTDC_OST_Canceled: Status.CANCELLED
}

DIRECTION_VT2CTP = {
    Direction.LONG: THOST_FTDC_D_Buy,
    Direction.SHORT: THOST_FTDC_D_Sell
}
DIRECTION_CTP2VT = {v: k for k, v in DIRECTION_VT2CTP.items()}
DIRECTION_CTP2VT[THOST_FTDC_PD_Long] = Direction.LONG
DIRECTION_CTP2VT[THOST_FTDC_PD_Short] = Direction.SHORT

ORDERTYPE_VT2CTP = {
    OrderType.LIMIT: THOST_FTDC_OPT_LimitPrice,
    OrderType.MARKET: THOST_FTDC_OPT_AnyPrice,
    OrderType.STOP: THOST_FTDC_OPT_AnyPrice,
}
ORDERTYPE_CTP2VT = {v: k for k, v in ORDERTYPE_VT2CTP.items()}

OFFSET_VT2CTP = {
    Offset.OPEN: THOST_FTDC_OF_Open,
    Offset.CLOSE: THOST_FTDC_OFEN_Close,
    Offset.CLOSETODAY: THOST_FTDC_OFEN_CloseToday,
    Offset.CLOSEYESTERDAY: THOST_FTDC_OFEN_CloseYesterday,
}
OFFSET_CTP2VT = {v: k for k, v in OFFSET_VT2CTP.items()}

EXCHANGE_CTP2VT = {
    "CFFEX": Exchange.CFFEX,
    "SHFE": Exchange.SHFE,
    "CZCE": Exchange.CZCE,
    "DCE": Exchange.DCE,
    "INE": Exchange.INE
}

PRODUCT_CTP2VT = {
    THOST_FTDC_PC_Futures: Product.FUTURES,
    THOST_FTDC_PC_Options: Product.OPTION,
    THOST_FTDC_PC_SpotOption: Product.OPTION,
    THOST_FTDC_PC_Combination: Product.SPREAD
}

OPTIONTYPE_CTP2VT = {
    THOST_FTDC_CP_CallOptions: OptionType.CALL,
    THOST_FTDC_CP_PutOptions: OptionType.PUT
}

MAX_FLOAT = sys.float_info.max
CHINA_TZ = pytz.timezone("Asia/Shanghai")


symbol_exchange_map = {}
symbol_name_map = {}
symbol_size_map = {}


class CtpGatewayEx(CtpGateway):
    # def __init__(self, event_engine):
    #     """Constructor"""
    #     # super().__init__(event_engine)
    #     print("CtpGatewayEx->after call super init")
    #     self.virtualtrader = False
    #     self.realTrading = False
    #     self.tradingLog = True
    #     self.current_date = datetime.now().strftime("%Y%m%d")

    def send_order(self, req: OrderRequest):
        print("ex Sendorder")
        # """
        # Send new order.
        # """
        # if self.virtualtrader:
        #     # logger.info(req)
        #     if req.offset not in OFFSET_VT2CTP:
        #         self.gateway.write_log("请选择开平方向")
        #         return ""

        #     if req.type not in ORDERTYPE_VT2CTP:
        #         self.gateway.write_log(f"当前接口不支持该类型的委托{req.type.value}")
        #         return ""

        #     self.order_ref += 1

        #     ctp_req = {
        #         "InstrumentID": req.symbol,
        #         "ExchangeID": req.exchange.value,
        #         "LimitPrice": req.price,
        #         "VolumeTotalOriginal": int(req.volume),
        #         "OrderPriceType": ORDERTYPE_VT2CTP.get(req.type, ""),
        #         "Direction": DIRECTION_VT2CTP.get(req.direction, ""),
        #         "CombOffsetFlag": OFFSET_VT2CTP.get(req.offset, ""),
        #         "OrderRef": str(self.order_ref),
        #         "InvestorID": self.userid,
        #         "UserID": self.userid,
        #         "BrokerID": self.brokerid,
        #         "CombHedgeFlag": THOST_FTDC_HF_Speculation,
        #         "ContingentCondition": THOST_FTDC_CC_Immediately,
        #         "ForceCloseReason": THOST_FTDC_FCC_NotForceClose,
        #         "IsAutoSuspend": 0,
        #         "TimeCondition": THOST_FTDC_TC_GFD,
        #         "VolumeCondition": THOST_FTDC_VC_AV,
        #         "MinVolume": 1
        #     }

        #     if req.type == OrderType.FAK:
        #         ctp_req["OrderPriceType"] = THOST_FTDC_OPT_LimitPrice
        #         ctp_req["TimeCondition"] = THOST_FTDC_TC_IOC
        #         ctp_req["VolumeCondition"] = THOST_FTDC_VC_AV
        #     elif req.type == OrderType.FOK:
        #         ctp_req["OrderPriceType"] = THOST_FTDC_OPT_LimitPrice
        #         ctp_req["TimeCondition"] = THOST_FTDC_TC_IOC
        #         ctp_req["VolumeCondition"] = THOST_FTDC_VC_CV

        #     self.reqid += 1
        #     self.reqOrderInsert(ctp_req, self.reqid)

        #     orderid = f"{self.frontid}_{self.sessionid}_{self.order_ref}"
        #     order = req.create_order_data(orderid, self.gateway_name)
        #     # self.gateway.on_order(order)
        #     trade = TradeData(
        #         symbol=order.symbol,
        #         exchange=order.exchange,
        #         orderid=order.orderid,
        #         tradeid=str(self.trade_count),
        #         direction=order.direction,
        #         offset=order.offset,
        #         price=order.price,
        #         volume=order.volume,
        #         datetime=order.datetime,
        #         gateway_name=order.gateway_name,
        #     )
        #     # trade = TradeData(gateway_name=order.gateway_name, symbol=order.symbol,
        #     #                   exchange=order.exchange, orderid=orderid,
        #     #                   direction=order.direction,
        #     #                   offset=order.offset,
        #     #                   price=order.price,
        #     #                   volume=order.volumem,
        #     #                   datetime=order.datetime,
        #     #                   investor=order.investor)
        #     self.gateway.on_trade(trade)
        #     return order.vt_orderid
        # else:
        #     super(CtpGatewayEx, self).send_order(req)
